<!-- 表格demo -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue Element UI Table Example</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <style>
    .edit-text {
      color: orange;
      cursor: pointer;
    }
    .ml10 {
      margin-left: 10px;
    }
  </style>
</head>
<body>
  <div id="app">
    <el-button type="primary" @click="addRow">添加</el-button>
    <el-table :data="tableData">
        <el-table-column prop="region" label="地区"></el-table-column>
        <el-table-column prop="score" label="访问量" sortable></el-table-column>
        <el-table-column label="编辑">
          <template slot-scope="{ row,$index }">
            <span class="edit-text" @click="editRow(row,$index)">修改</span>
            <span class="edit-text ml10" @click="deleteRow(row,$index)">删除</span>
          </template>
        </el-table-column>
      </el-table>

    <el-dialog :title="methodType=='edit'?'编辑地区':'添加地区'" :visible.sync="dialogVisible" width="600px">
      <el-form :model="editedItem" label-width="80px">
        <el-form-item label="地区">
          <el-input v-model="editedItem.region" controls-position="right"></el-input>
        </el-form-item>
        <el-form-item label="访问量">
          <el-input-number v-model="editedItem.score" controls-position="right"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>

  <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui@2.15.6/lib/index.js"></script>
  <script>

new Vue({
      el: '#app',
      data() {
        return {
          tableData: [],
          dialogVisible: false,
          editedItem: {},
          methodType: null,
        };
      },
      created() {
        this.fetchData();
      },
      methods: {
        async fetchData() {
          try {
            let response = await fetch('./data.json');
            let data = await response.json();
            this.tableData = data;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        },
        // ... 其他方法 ...
        addRow() {
          // 添加行逻辑
          this.methodType = "add";
          this.editedItem = {};
          this.dialogVisible = true;
        },

        editRow(row,index) {
          this.methodType = "edit";
          this.editedItem = Object.assign({}, row);
          this.dialogVisible = true;
        },
        saveEdit() {
          let _this = this;
          if (this.methodType = "edit") { // 修改保存
            fetch("/saveUrl",{
              method: "POST",
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(this.editedItem)
            }).then(function(res){
              return res.json()
            }).then(function(data){
              console.log(data)
              _this.$message({ message:"修改成功", type:"success" })
              _this.fetchData()
              _this.dialogVisible = false;
            }).catch(function(e){
              console.error(e)
              _this.$message({ message:"修改失败", type:"error" })
            })
          } else if (this.methodType = "add") { // 添加保存
            fetch("/addUrl",{
              method: "POST",
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(this.editedItem)
            }).then(function(res){
              return res.json()
            }).then(function(data){
              console.log(data)
              _this.$message({ message:"添加成功", type:"success" })
              _this.fetchData()
              _this.dialogVisible = false;
            }).catch(function(e){
              console.error(e)
              _this.$message({ message:"添加失败", type:"error" })
            })
          }
          
          // let index = this.tableData.findIndex(item => item === this.editedItem);
          // if (index > -1) {
          //   this.tableData.splice(index, 1, this.editedItem);
          // }
          // this.dialogVisible = false;
        },
        deleteRow(row,$index) {
          // 删除行逻辑
          this.$confirm('确认删除吗？', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.tableData.splice($index, 1);
          })
          .catch(() => {});
          // let index = this.tableData.findIndex(item => item === row);
          //   if (index > -1) {
          //       this.tableData.splice(index, 1);
          //   }
          
        }
      }
    });

  </script>
</body>
</html>
